package com.tiger.cloud.mybatis.gen.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;

public class DataTableUtil {

	public static String insertResource(String tableName, String sufixName, String url, boolean isMenu, String parentId_) throws SQLException {
		String date = DateTimeUtil.formatDateTimetoString(new Date());
		Connection conn = DBUtils.getConn();
		java.sql.Statement s = conn.createStatement();
		String resourceId = String.valueOf(new IdWorker().getId());
		String parentId = parentId_;
		if (StringUtils.isEmpty(parentId)) {
			parentId = String.valueOf(new IdWorker().getId());
		}
		String cNmaeString = DBUtils.genertorTableChinseNames.get(tableName);
		cNmaeString = cNmaeString == null ? "" : cNmaeString + sufixName;
		String sql = null;
		if (StringUtils.isEmpty(url)) {
			sql = "select count(1) as count from  sys_resource r where r.name='" + cNmaeString + "'";
		} else {
			sql = "select count(1) as count from  sys_resource r where r.url='" + url + "'";
		}
		System.out.println(sql);
		ResultSet rs = s.executeQuery(sql);
		rs.next();
		long count = rs.getLong("count");
		s.close();
		conn.close();
		if (count == 0) {
			Connection conn2 = DBUtils.getConn();
			java.sql.Statement s2 = conn2.createStatement();
			String r1 = null;
			if (StringUtils.isEmpty(url)) {
				r1 = "INSERT INTO `sys_resource` (`id`, `name`, `url`, `remark`, `parent_id`, `structure`, `sort_no`, `create_user`, `create_date`, `update_user`, `update_date`, `is_menu`) "
						+ "VALUES ('"
						+ resourceId
						+ "', '"
						+ cNmaeString
						+ "', NULL, '"
						+ parentId
						+ "', NULL, '', '"
						+ resourceId
						+ "', 'system', '"
						+ date
						+ "', 'system', '" + date + "', '" + (isMenu == true ? 1 : 2) + "');";
			} else {
				r1 = "INSERT INTO `sys_resource` (`id`, `name`, `url`, `remark`, `parent_id`, `structure`, `sort_no`, `create_user`, `create_date`, `update_user`, `update_date`, `is_menu`) "
						+ "VALUES ('"
						+ resourceId
						+ "', '"
						+ cNmaeString
						+ "','"
						+ url
						+ "', NULL, '"
						+ parentId
						+ "', '', '"
						+ resourceId
						+ "', 'system', '"
						+ date + "', 'system', '" + date + "', '" + (isMenu == true ? 1 : 2) + "');";

			}
			System.out.println(r1);
			s2.executeUpdate(r1);
			conn2.close();
			s2.close();

			Connection conn3 = DBUtils.getConn();
			java.sql.Statement s3 = conn3.createStatement();
			String r2 = "INSERT INTO `sys_role_resource`(`role_id`, `resource_id`) VALUES ('1', '" + resourceId + "');";
			s3.executeUpdate(r2);
			System.out.println(r2);
			conn3.close();
			s3.close();
		}
		return resourceId;
	}

}
